package com.example.customview.scrollevent.more

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.ListView

class MoreListView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null,
    defaultStyle: Int = 0
) : ListView(context, attributeSet, defaultStyle) {

    /*  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
          val measureSpec =  View.MeasureSpec.makeMeasureSpec(
              Integer.MAX_VALUE shr 2, View.MeasureSpec.AT_MOST
          )
          super.onMeasure(widthMeasureSpec, measureSpec)

      }*/
    /**
     * 内部拦截法
     */
    private var mLastY: Float = 0f

    @Override
    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                parent.requestDisallowInterceptTouchEvent(true)
            }

            MotionEvent.ACTION_MOVE -> {
                //满足listView滑动到顶部，如果继续下滑，那就允许scrollView拦截事件
                if (firstVisiblePosition == 0 && (event.y - mLastY) > 0) {
                    //允许ScrollView拦截事件
                    parent.requestDisallowInterceptTouchEvent(false)
                } else if (lastVisiblePosition == count - 1 && (event.y - mLastY) < 0) {
                    parent.requestDisallowInterceptTouchEvent(false);
                }else{
                    parent.requestDisallowInterceptTouchEvent(true);
                }

            }

            MotionEvent.ACTION_UP -> {}
            else -> {}
        }
        mLastY = event.y
        return super.dispatchTouchEvent(event)
    }

}